package com.hucsmn.stumansys.servlet.admin;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.hucsmn.stumansys.service.AdminService;
import com.hucsmn.stumansys.utils.ConvertUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

/**
 * 管理员账户名列表查询 API。
 *
 * 接收 HTTP 参数
 *      prefix  查询管理员账户名前缀。可选。
 *
 * 响应 JSON 数据
 *      code    状态码。0 表示成功，1 表示查询失败。
 *      msg     操作出错原因。
 *      data    账户名列表。字符串数组类型。
 *
 * @author hucsmn
 */
@WebServlet("/api/admin/names")
public class AdminNamesServlet extends HttpServlet {
    private final AdminService adminService = AdminService.getInstance();
    private final Gson gson = new GsonBuilder().create();

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=UTF-8");

        String prefix = ConvertUtils.normalizeText(request.getParameter("prefix"));
        JsonObject result = new JsonObject();
        List<String> names = adminService.names(prefix);
        if (names != null) {
            result.addProperty("code", 0);
            result.addProperty("msg", "");
            result.add("data", gson.toJsonTree(names));
        } else {
            result.addProperty("code", 1);
            result.addProperty("msg", "无法获取管理员账户名列表");
        }

        PrintWriter out = response.getWriter();
        out.write(gson.toJson(result));
        out.flush();
        out.close();
    }
}
